<template>
  <div class="content myFlex-x">
    <div class="game-container">
      <el-scrollbar height="900px" @end-reached="loadMore">
        <div class="gameList">
          <div
              class="game"
              @click="goDetail(game)"
              v-for="(game, index) in gameList"
              :key="index"
          >
            <div class="game-left">
              <img :src="require('@/assets/img/' + game.img)" alt="game-img" />
              <div class="gameName">{{ game.name }}</div>
            </div>
            <div class="game-type">{{ game.type }}</div>
            <div class="game-cart">添加至购物车</div>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { require } from "@/utils/getFileUrl.ts";
import request from "@/utils/request.ts";
import { ElMessage } from "element-plus";
import { router } from "@/router/router.ts";

let gameName = ref('')
let gameList = ref([])
let pageCurrent = ref(1)
let pageSize = ref(10)
// 用于控制是否正在加载，防止重复请求
let isLoading = ref(false)

onMounted(() => {
  searchGame()
})

function searchGame() {
  // 标记为加载中
  isLoading.value = true
  request.get("/getGamePageList", {
    params: {
      pageCurrent: pageCurrent.value,
      pageSize: pageSize.value,
      gameName: gameName.value
    }
  })
      .then((res) => {
        if (pageCurrent.value > 1) {
          gameList.value = gameList.value.concat(res.data.records)
        } else {
          gameList.value = res.data.records
        }
        isLoading.value = false
      })
      .catch((err) => {
        ElMessage.error(err)
        isLoading.value = false
      })
}

// 无限滚动触发的加载函数
function handleInfiniteScroll() {
  // 若正在加载或没有更多数据，直接返回（需结合实际是否有更多数据逻辑，这里简单示例）
  if (isLoading.value) return
  pageCurrent.value++
  searchGame()
}

function goDetail(game) {
  router.push({ path: "/details", query: { game: JSON.stringify(game) } })
}
</script>

<style scoped>
@import "@/assets/css/gameslist.css";
</style>